package cn.tangsihai.hrm.service.impl;

import cn.tangsihai.hrm.constant.Constants;
import cn.tangsihai.hrm.domain.Login;
import cn.tangsihai.hrm.dto.LoginAndMealId;
import cn.tangsihai.hrm.mapper.LoginMapper;
import cn.tangsihai.hrm.service.ILoginService;
import cn.tangsihai.hrm.service.IMealService;
import cn.tangsihai.hrm.util.AssertUtil;
import cn.tangsihai.hrm.util.HttpUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author sihai.tang
 * @since 2021-11-22
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private IMealService mealServicer;

    /**
     * 保存login、和login_meal表的数据
     * @param loginAndMealId
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Login saveLoginAndMeal(LoginAndMealId loginAndMealId) {
        // 校验参数
        Login login = loginAndMealId.getLogin();
        Long mealId = loginAndMealId.getMealId();
        if (login == null || mealId == null){
            throw new RuntimeException("请正确填写信息");
        }
        // 准备login表数据
        Login login1 = initLogin(login);
        // 保存login表数据,并获取自增长id信息
        loginMapper.insert(login1);

        // 保存login_meal表数据
        mealServicer.saveLoginMeal(login1.getId(), mealId);
        return login1;
    }

    /**
     * 保存login表的数据
     * @param login
     * @return
     */
    @Override
    public Login saveLogin(Login login) {
        // 保存login表数据,并获取自增长id信息
        loginMapper.insert(login);
        return login;
    }

    @Override
    public Login selectOneByUserName(String username) {
        return loginMapper.selectOneByUserName(username);
    }


    /**
     * 准备数据
     */
    private Login initLogin(Login login) {
        Login login1 = new Login();
        login1.setUsername(login.getUsername());
        login1.setPassword(login.getPassword());
        login1.setType(Constants.Login.TYPE_BACKGROUND);
        login1.setEnabled(true);
        login1.setAccountNonExpired(true);
        login1.setAccountNonLocked(true);
        login1.setCredentialsNonExpired(true);
        return login1;
    }

    /**
     * 用户登录
     *      1.校验参数
     *      2.根据用户名查询数据
     *      3.判断登录用户时前台登录还是后台登录
     *      4.拼接获取token的网址
     *      5.发送http请求
     *      6.获取token返回
     * @param login
     */
    // 加载配置文件中的密码模式获取token的url
    @Value("${oauth2.url.token-password}")
    private String urlTokenPassword;

    // 加载配置文件中的客户端密文---后台用户
    @Value("${oauth2.client-secret-admin}")
    private String clientSecretAdmin;

    // 加载配置文件中的客户端密文---前台用户
    @Value("${oauth2.client-secret-website}")
    private String clientSecretWebsite;
    @Override
    public Map<String, String> userLogin(Login login) {
        // 1.校验参数
        AssertUtil.isNotEmpty(login.getUsername(), "用户名不能为空");
        AssertUtil.isNotEmpty(login.getPassword(), "密码不能为空");

        // 2.根据用户名查询数据
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", login.getUsername());
        Login loginFromDB = super.selectOne(wrapper);

        // 3.判断登录用户时前台登录还是后台登录
        AssertUtil.isNotNull(loginFromDB, "用户名不存在");
        String clientId = "";
        String clientSecret = "";
        if (loginFromDB.getType() == Constants.Login.TYPE_BACKGROUND){
            // 后台用户
            clientId = "admin";
            clientSecret = clientSecretAdmin;
        } else {
            // 前台用户
            clientId = "website";
            clientSecret = clientSecretWebsite;
        }

        // 4.拼接获取token的网址
        String url = String.format(urlTokenPassword, clientId, clientSecret, login.getUsername(), login.getPassword());

        // 5.发送http请求，获取token返回
        Map<String, String> map = HttpUtil.sendPost(url);
//        AssertUtil.isNotEmpty (map.get("access_token"), "密码错误或密码");
        return map;
    }
}
